<template>
    <div class="app-container">
        <component :is="pipelineNetwork" />
        <div class="cesium-map">
            <div id="cesiumContainer" ref="cesiumContainer" :style="{ width: `calc(100vw - ${containerOffsetLeft})`, height: `calc(100vh - ${containerOffsetTop})` }"></div>

            <!-- 自定义弹框 -->
            <div v-if="showPopup" :style="popupStyle" class="popup">
                <p>物体位置: {{ popupInfo }}</p>
                <button @click="closePopup">关闭</button>
            </div>
        </div>
    </div>
</template>

<script setup name="Dispatch-cockpit">
import * as Cesium from 'cesium';
import { onMounted, nextTick, ref } from 'vue';

Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI2MzlmOGQxZi05M2UwLTQ3NzItYTlhNS03N2NkMDgxYzMyMjkiLCJpZCI6MTg4NDY1LCJpYXQiOjE3MzkyMDMyOTR9.a6XM6flLYaqGnrIfPfCu8BWE7TSeI8ps-C1A_2wlvqc';

const pipelineNetwork = ref(null);
const cesiumContainer = ref(null);
const showPopup = ref(false);
const popupInfo = ref('');
const popupStyle = ref({ top: '0px', left: '0px' });
let viewer = null;
let lastClickCartesian = null; // 存储点击的地图坐标
let lastClickScreenPosition = null; // 存储点击的屏幕坐标
const containerOffsetLeft = ref('200px');
const containerOffsetTop = ref('85px');

onMounted(async () => {
    viewer = new Cesium.Viewer('cesiumContainer', {
        timeline: false,
        animation: false,
        geocoder: false,
        homeButton: false,
        sceneModePicker: false,
        baseLayerPicker: false,
        navigationHelpButton: false,
        fullscreenButton: false,
        terrain: Cesium.Terrain.fromWorldTerrain({
            requestWaterMask: true,
        }),
    });

    const osmBuildings = await Cesium.Cesium3DTileset.fromIonAssetId(96188);
    viewer.scene.primitives.add(osmBuildings);

    generateRandomPolylines(viewer);

    viewer.scene.globe.tileLoadProgressEvent.addEventListener(function (remainingTiles) {
        if (remainingTiles === 0 && !pipelineNetwork.value) {
            console.log('全球地形和影像加载完成');
        }
    });

    viewer.zoomTo(viewer.entities).then(() => {
        nextTick(async () => {
            const component = await import('@/components/PipelineNetwork');
            pipelineNetwork.value = component.default;
        });
    });

    // 点击事件处理
    viewer.screenSpaceEventHandler.setInputAction(function (click) {
        // 获取点击的物体
        const pickedObject = viewer.scene.pick(click.position);

        if (Cesium.defined(pickedObject)) {
            // 获取点击位置的地图坐标
            lastClickCartesian = viewer.scene.pickPosition(click.position);


            if (lastClickCartesian) {
                const cartographic = Cesium.Cartographic.fromCartesian(lastClickCartesian);
                const longitude = Cesium.Math.toDegrees(cartographic.longitude);
                const latitude = Cesium.Math.toDegrees(cartographic.latitude);

                popupInfo.value = `经度: ${longitude.toFixed(5)}, 纬度: ${latitude.toFixed(5)}`;
                lastClickScreenPosition = click.position;


                showPopup.value = true;

                updatePopupPosition();
            }


            
            // 飞向点击位置
            flyToPosition(lastClickCartesian)
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

    // 每帧渲染后更新弹框位置
    viewer.scene.postRender.addEventListener(updatePopupPosition);
});

// 飞向指定位置的函数
function flyToPosition(position) {
    return viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromRadians(
            Cesium.Cartographic.fromCartesian(position).longitude,
            Cesium.Cartographic.fromCartesian(position).latitude,
            2000 // 提高高度适应 -45° 视角
        ),
        orientation: {
            pitch: Cesium.Math.toRadians(-90), // 斜向下看
            roll: 0.0
            // 不指定 heading，让 Cesium 自动计算
        },
        duration: 2
    });
}
// 更新弹框位置
function updatePopupPosition() {
    const react = cesiumContainer.value.getBoundingClientRect();
    console.log(react);
    
    containerOffsetLeft.value = react.left + 'px';
    containerOffsetTop.value = react.top + 'px';
    
    if (!showPopup.value || !lastClickCartesian) return;

    // 将地图坐标转换为当前屏幕坐标
    const newScreenPosition = viewer.scene.cartesianToCanvasCoordinates(
        lastClickCartesian
    );

    if (newScreenPosition) {
        popupStyle.value = {
            left: `${newScreenPosition.x + 10}px`,
            top: `${newScreenPosition.y + 10}px`,
        };
    }




}
// 关闭弹框
function closePopup() {
    showPopup.value = false;
    lastClickCartesian = null;
    lastClickScreenPosition = null;
}

// 生成随机线条函数
function generateRandomPolylines(viewer) {
    const center = Cesium.Cartesian3.fromDegrees(114.350411, 30.607792);
    const entities = viewer.entities;

    const positions = [];
    for (let j = 0; j < 10; j++) {
        const offset = 0.1 * Math.random();
        const lon = 114.350411 + (Math.random() - 0.5) * offset;
        const lat = 30.607792 + (Math.random() - 0.5) * offset;
        positions.push(Cesium.Cartesian3.fromDegrees(lon, lat));
    }

    entities.add({
        name: '随机线',
        polyline: {
            positions: positions,
            width: 10,
            material: new Cesium.PolylineGlowMaterialProperty({
                glowPower: 0.2,
                color: Cesium.Color.fromRandom({ alpha: 0.8 }),
            }),
            clampToGround: true,
        },
    });
}
</script>

<style scoped lang="scss">
.app-container {
    padding: 0 !important;
    overflow: hidden;
    position: relative;
}

.cesium-map {
    position: relative;
}

#cesiumContainer {
    width: 100vw;
    height: 100vh;
}

:deep(.cesium-viewer-bottom) {
    display: none;
}

.popup {
    position: absolute;
    background: rgba(0, 0, 0, 0.8);
    color: white;
    padding: 10px 15px;
    border-radius: 5px;
    z-index: 9999;
    border: 1px solid #2a8ceb;
    pointer-events: auto;
    transform: translate(-50%, -100%);
    width: 300px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);

    button {
        margin-top: 8px;
        padding: 4px 8px;
        background: #2a8ceb;
        color: white;
        border: none;
        border-radius: 3px;
        cursor: pointer;

        &:hover {
            background: #1a6fcb;
        }
    }
}
</style>